import { Injectable, BadRequestException, Inject } from '@nestjs/common';
import { InjectEntityManager } from '@nestjs/typeorm';
import { EntityManager } from 'typeorm';
import { User } from './entities/user.entity';
import { EmailService } from 'src/email/email.service';
import { RedisService } from 'src/redis/redis.service';

@Injectable()
export class UserService {
  @InjectEntityManager()
  entityManager: EntityManager;

  @Inject(EmailService)
  emailService: EmailService;

  @Inject(RedisService)
  redisService: RedisService;

  async getCaptcha(username: string) {
    const findUser = await this.entityManager.findOne(User, {
      where: {
        username,
      },
    });

    if (findUser) {
      throw new BadRequestException('该用户已注册了');
    }

    const captcha = Math.random().toString().slice(2, 8);

    try {
      await this.emailService.sendMail({
        to: username,
        subject: '注册验证码',
        html: `<p>你的注册验证码是 ${captcha}</p>`,
      });

      await this.redisService.set(
        `register_captcha_${username}`,
        captcha,
        5 * 60,
      );

      return '验证码已发送成功';
    } catch (error) {
      console.log(error);
      throw new BadRequestException('验证码发送失败');
    }
  }

  async register(user) {
    const captcha = await this.redisService.get(
      `register_captcha_${user.username}`,
    );

    if (!captcha) {
      throw new BadRequestException('没有找到相关的验证码，请重新获取');
    }

    if (captcha !== user.captcha) {
      throw new BadRequestException('验证码错误，请重新输入');
    }

    const findUser = await this.entityManager.findOne(User, {
      where: {
        username: user.username,
      },
    });

    if (findUser) {
      throw new BadRequestException('该邮箱已注册了');
    }

    if (user.password !== user.confirmPassword) {
      throw new BadRequestException('两次密码不一致，请重新输入');
    }

    try {
      await this.entityManager.save(User, {
        username: user.username,
        password: user.password,
      });

      return '注册成功';
    } catch (error) {
      return '注册失败';
    }
  }

  async login(user) {
    // try {
      const foundUser = await this.entityManager.findOne(User, {
        where: {
          username: user.username,
        },
      }) || null;
      
      if (!foundUser) {
        throw new BadRequestException('用户名不正确');
      }

      if (foundUser.password !== user.password) {
        throw new BadRequestException('密码不正确');
      }
      
      return foundUser;

    // } catch (error) {
    //   throw new BadRequestException('登录失败');
    // }
  }
}
